package com.zxq.web.channel;

import com.zxq.web.config.LockConfig;
import com.zxq.web.dto.PlatformCmdDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;


@Component
@Slf4j
public class SynchronismMessage {


    @Autowired
    LockConfig lockConfig;


    /**
     * 锁
     */
    ConcurrentHashMap<String,Object> locks = new ConcurrentHashMap<>();

    /**
     * 数据
     */
    ConcurrentHashMap<String,PlatformCmdDTO> datas = new ConcurrentHashMap<>();


    /**
     * 阻塞平台消息，用来处理同步
     * @param devId 设备id
     * @param cmdId 指令id
     * @return
     */
    @SneakyThrows
    public  PlatformCmdDTO waitCmdMessage(String devId,Long cmdId) {
        PlatformCmdDTO result = null;
        String key =  generateCmdKey(devId,cmdId);
        if(locks.get(key) == null) {
            locks.put(key,new Object());
        }
        Object object = locks.get(key);
        if(datas.get(key) != null) {
            datas.remove(key);
        }
        object.wait(lockConfig.getTimeOut());
        result = datas.get(key);
        return result;
    }

    /**
     * 唤醒平台消息，用来处理同步
     * @param platformCmdDTO
     */
    public  void notifyPlatformMessage(String devId,Long cmdId,PlatformCmdDTO platformCmdDTO) {
       String key = generateCmdKey(devId,cmdId);
       if(locks.get(key) == null) {
           log.info(String.format("key:{0} not find unit lock,please check your mysql data!",key));
           return;
       }
       datas.put(key,platformCmdDTO);
       locks.get(key).notify();
    }



    static String blockKey = "dev:{0}-cmd:{2}";
    /**
     * 生产阻塞的key，阻塞当前线程
     * @param devId 设备id
     * @param cmdId   指令id
     * @return
     */
    private static String generateCmdKey(String devId,Long cmdId) {
        String key = String.format(blockKey,devId,cmdId);
        return key;
    }






}
